/**
 * Created by Administrator on 2017/3/10.
 */
var crypto = require('crypto');
var globalVar = require('../global_var');
var request = require('request');

(function () {
    var randomString = this.randomString = function (len) {
        len = len || 32;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        var maxPos = $chars.length;
        var pwd = '';
        for (var i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    };

    var simpleDateFormat = this.simpleDateFormat = function (time) {
        var d = new Date(time);
        var month = d.getMonth()+1;
        if(month<10){
            month = '0'+month;
        }
        var date = d.getDate();
        if(date<10){
            date = '0'+date;
        }
        var hour = d.getHours();
        if(hour<10){
            hour = '0'+hour;
        }
        var minute = d.getMinutes();
        if(minute<10){
            minute = '0'+minute;
        }
        var second = d.getSeconds();
        if(second<10){
            second = '0'+second;
        }
        return d.getFullYear() + '-' + month + '-' + date +' '+hour+':'+minute+':'+second;
    }

    var formatTime = this.formatTime = function(str) {
        if (str.indexOf('.000Z') >= 0) {
            str = str.replace(/T/, ' ');
            str = str.replace(/.000Z/, ' ');
            var a1;
            var a2;
            a1 = str.split(' ');
            a2 = a1[1].split(':');
            a2[0] = parseInt(a2[0]) + 8;
            if (a2[0] >= 24) {
                a1[0] = a1[0].split('-');
                a1[0][2] = parseInt(a1[0][2]) + 1;
                a1[0] = a1[0].join('-');
                a2[0] = a2[0] - 24;
                if (a2[0] < 10) {
                    a2[0] = '0' + a2[0];
                }
            }
            a2 = a2.join(':');
            var update_time = a1[0] + ' ' + a2;
            return update_time;
        } else {
            return str;
        }
    };

    var getDatePoor = this.getDatePoor = function (endDate,nowDate) {

        var nd = 1000 * 24 * 60 * 60;
        var nh = 1000 * 60 * 60;
        var nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        var str = '';
        var diff = endDate - nowDate;
        // 计算差多少天
        var day = Math.floor(diff / nd);
        if(day != 0){
            str +=  day +'天';
        }
        // 计算差多少小时
        var hour = Math.floor(diff % nd / nh);
        if(hour != 0){
            str +=  hour +'小时';
        }
        // 计算差多少分钟
        var min = Math.floor(diff % nd % nh / nm);
        if(min != 0){
            str +=  min +'分钟';
        }
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return str;
    }

    function convertToUnicode(data) {
        var reg = /\\u[0-9a-f]{4}/igm;
        return data.replace(reg, function () {
            return String.fromCharCode(parseInt(arguments[0].substr(2, 4), 16).toString())
        });
    };
    var getIp4 = this.getIp4 = function(ip) {//去掉::ffff:
        if (ip.length > 15)
        {
            var nyIP = ip.slice(7);
            ip = nyIP;
        }
        return ip;
    };

    var getClientIp = this.getClientIp = function (req) {
        return req.headers['x-forwarded-for'] ||
            req.connection.remoteAddress ||
            req.socket.remoteAddress ||
            req.connection.socket.remoteAddress;
    };

    //计算sign
    var getAppSign = this.getAppSign = function (APP_key,APP_secret,t){

        var md5=crypto.createHash('md5');
        md5.update(""+APP_key+APP_secret+t);
        var sign = md5.digest('hex');
        console.log(t);
        return sign;
    }

    var getPartnerSign = this.getPartnerSign = function (secret, t){

        var md5=crypto.createHash('md5');
        md5.update("" + t + secret + t);
        var sign = md5.digest('hex');
        return sign;
    }

    var checkOvertime = this.checkOvertime = function (t) {
        var time = new Date().getTime();
        if(parseInt((time - t)/1000) > 120) {
            return false;
        } else {
            return true;
        }
    }

    var checkPartnerSign = this.checkPartnerSign = function (secret, param) {
        var partnerSign = param.sign;
        delete param.sign;
        var allKeys = [];
        for(var k in param) allKeys.push(k);
        allKeys.sort();
        var sign = '';
        allKeys.forEach(function (t) {
            var str = ['size','page','pi_id','start'];
            console.log(str.indexOf(t));
            if(str.indexOf(t) < 0) sign += param[t];
        })
        sign += secret;
        var md5 = crypto.createHash('md5');
        md5.update(sign);
        sign = md5.digest('hex');
        if(sign == partnerSign) {
            return true;
        } else {
            return false;
        }
    }

    var partnerSign = this.checkPartnerSign = function (secret, param) {
        var partnerSign = param.sign;
        delete param.sign;
        var allKeys = [];
        for(var k in param) allKeys.push(k);
        allKeys.sort();
        var sign = '';
        allKeys.forEach(function (t) {
            var str = ['size','page','pi_id','start'];
            console.log(str.indexOf(t));
            if(str.indexOf(t) < 0) sign += param[t];
        })
        sign += secret;
        var md5 = crypto.createHash('md5');
        md5.update(sign);
        sign = md5.digest('hex');
        return sign;
    }

    var getParWithSign = this.getParWithSign = function (APP_key,APP_secret) {
        var time = new Date().getTime();
        var par = {
            app_key: APP_key,
            app_time: time,
            app_sign: getAppSign(APP_key,APP_secret,time)
        }
        return par;
    }

    var checkSrvConnection = this.checkSrvConnection = function (par) {
        var sign = getAppSign(par.app_key,globalVar.apps[par.app_key], par.app_time);
        return sign == par.app_sign ? true : false;
    }

    var baseRequest = this.baseRequest = function(host, path, param, callback) {
        var url = host + path;
        var form = '';
        for(var key in param){
            form += key + '='  + param[key] + '&';
        }
        var options = {
            url: url,
            method: 'POST',
            form: form
        };
        request(options, function (error, response, body) {
            if (error || !response || response.statusCode != 200 || !body) {
                callback('服务器异常，请稍后重试');
                console.log(error);
                return;
            } else {
                try {
                    body = JSON.parse(body);
                    if(body.status == 200){
                        callback(null,body.payload);
                        return;
                    }
                    callback(body.err);
                } catch (e) {
                    callback('服务器异常，请稍后重试');
                }
            }
        });
    }
     var isEmptyObj = this.isEmptyObj = function isEmptyObj(obj) {
         for(var key in obj){
             return false;
         }
         return true;
     }
    /*
     *
     用法示例:简单版本
     var param = {
         par:data,
         findKeys: ['app_sid','vip_sid'],
         selectStr: '*',
         fromStr: 'order_list',
         DBFactory:DBFactory,
         page:data.page,
         pageSize:data.pageSize
     };
     dbBaseList(param,cb);
     扩展版本：
     var param = {
         par:data,
         findKeys: ['app_sid','vip_sid','account'],
         findKeysObj:{
             app_sid:{
                tableName:'ol'
             },
             vip_sid:{
                tableName:'ol',
             },
             account:{
                 tableName:'u'
             },
         },
         selectStr: 'ol.*,u.account',
         fromStr: ' order_list ol left join users u on ol.uid = u.uid ',
         DBFactory:DBFactory,
         page:data.page,
         pageSize:data.pageSize,
         startTime:data.startTime,
         endTime:data.endTime,
         timeKey:'created_time'
     };
     dbBaseList(param,cb);
     * */
    var dbBaseList = this.dbBaseList = function (data,cb) {
        var par = data.par;
        var findKeys = data.findKeys;
        var findKeysObj = data.findKeysObj;
        var DBFactory = data.DBFactory;
        var selectStr = data.selectStr;
        var fromStr = data.fromStr;
        var startTime = data.startTime;
        var endTime = data.endTime;
        var timeKey = data.timeKey;
        var orderByObj = data.orderByObj;
        var sqlCount = ' SELECT count(*) AS total FROM ' + fromStr;
        var sql = 'SELECT ' + selectStr + ' FROM ' + fromStr;
        var baseSql = ' WHERE 1 ';
        var value = [];
        if (startTime) {
            baseSql += ' AND ' + timeKey + ' >= ? ';
            value.push(startTime);
        }
        if (endTime) {
            baseSql += ' AND ' + timeKey + ' <= ? ';
            value.push(endTime);
        }
        for (var i = 0; i < findKeys.length; i++) {
            var key = findKeys[i];
            if (par[key] != undefined) {
                var findKeyObj = findKeysObj[key];
                var sqlKey = key; //实际查询时的key写法，有可能带上 表名.字段
                var sqlMark = '='; //实际查询时符号
                var sqlValue = '?'; //实际查询时的值
                if (findKeyObj)  {
                    if (findKeyObj.tableName) sqlKey = findKeyObj.tableName + '.' + key;
                    if (findKeyObj.specialMark) sqlMark = findKeyObj.specialMark;
                    if (findKeyObj.sqlValue) sqlValue = findKeyObj.sqlValue;
                }
                baseSql += ' AND ' + sqlKey + ' ' + sqlMark + ' ' + sqlValue;
                if (!findKeyObj || !findKeyObj.sqlValue) value.push(par[key]);
            }
        }
        sqlCount += baseSql;
        sql += baseSql;
        if (orderByObj && orderByObj.orderKey) sql += ' order by ' + orderByObj.orderKey;
        if (orderByObj && orderByObj.orderSort) sql += ' ' + orderByObj.orderSort;
        var pageSize = data.pageSize ? data.pageSize : 10;
        var page = data.page ? data.page : 1;
        sql += ' LIMIT ' + (page - 1) * pageSize + ',' + pageSize;
        DBFactory.poolQueryList(sql,sqlCount,value,cb);
    };
})();